package com.example.demo.controller;

import com.example.demo.Service.UserService;
import com.example.demo.model.User;
import com.example.demo.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/add")
    public JsonData addUser(@RequestBody User user){
        Integer result = userService.addUser(user);
        if(result == -1){
            return JsonData.buildError("用户已存在");
        } else if(result == 0){
            return JsonData.buildError("新增用户失败");
        }else {
            return JsonData.buildSuccess(result);
        }
    }


    @PostMapping("/modify")
    public JsonData modifyUser(@RequestBody User user){
        Integer result = userService.modifyUser(user);
        if(result == null){
            return JsonData.buildError("获取用户列表失败");
        }else {
            return JsonData.buildSuccess(result);
        }
    }

    @GetMapping("/get/list")
    public JsonData getUserList(){
        List<User> result = userService.getUserList();
        if(result == null){
            return JsonData.buildError("获取用户列表失败");
        }else {
            return JsonData.buildSuccess(result);
        }
    }

    @PostMapping("/get")
    public JsonData getUser(@RequestBody Map<String, Integer> user){
        User result = userService.findUser(user.get("user_id"));
        if(result == null){
            return JsonData.buildError("没有此用户");
        }else {
            return JsonData.buildSuccess(result);
        }
    }

    @PostMapping("/delete")
    public JsonData deleteUser(@RequestBody Map<String, Integer> user){
        Integer result = userService.deleteUser(user.get("user_id"));
        if(result == 0){
            return JsonData.buildError("删除失败");
        }else {
            return JsonData.buildSuccess(result);
        }
    }


}
